<template>
	<view class="pks_page">
		<Nvagatmy :images="img" />
		<view class="main">
			<view class="price_tab">
				<view class="price_tab_item" :class="{ active: priceTabIndex === index }"
					v-for="(item, index) in priceTabList" :key="index" @click="priceTabClick(index)">
					{{ item.title }}
				</view>
			</view>
			<view class="list_box">
				<view class="status_box" v-if="activeTab != 'history'">
					<view class="status_item" :class="{ active: statusTabIndex === index }"
						v-for="(item, index) in statusTabList" :key="index" @click="statusTabClick(index)">
						{{ item.title }}
					</view>
				</view>
				<scroll-view class="lists_box" scroll-y="true" @scrolltolower="loadMore" style="height: 1050rpx;">
					<view class="scroll_list">
						<view class="list_item" v-for="(item, index) in sortedRooms" :key="index"
							@click="handleRoomClick(item)">
							<view class="top">
								<view class="header">
									{{ item.game_mode == 1 ? "欧皇" : "非酋" }}模式
								</view>
								<view class="user_box">
									<view class="user_item" v-for="userIndex in item.user_num" :key="userIndex"
										:style="(item.game_arena_player[userIndex - 1] && item.game_arena_player[userIndex - 1].user) ? 'background-image: url(' + item.game_arena_player[userIndex - 1].user.avatar + ')' : ''">
										<template
											v-if="!(item.game_arena_player[userIndex - 1] && item.game_arena_player[userIndex - 1].user)">
											+
										</template>
									</view>
								</view>
								<view class="tool_list">
									<view class="scroll_tool_list">
										<view class="tool_item" v-for="(toolItem, toolIndex) in item.game_arena_box"
											:key="toolIndex">
											<view class="img"
												:style="'background-image: url(' + toolItem.box.intact_cover + ')'"></view>
											<view class="price">
												<view class="icon">

												</view>
												<view class="text">
													{{ toolItem.box.game_bean }}
												</view>
											</view>
										</view>
									</view>
								</view>
							</view>
							<view class="bottom">
								<view class="list_btn" v-if="activeTab == 'roomList'">
									<view class="icon">

									</view>
									<view class="text">
										{{ item.total_bean }}&nbsp;加入
									</view>
								</view>
								<view class="list_btn" v-else>
									<view class="text">
										查看
									</view>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>

				<!-- Loading状态 -->
				<view class="loading-state" v-if="waiting">
					<view class="loading-spinner"></view>
					<text class="loading-text">数据加载中...</text>
				</view>

				<!-- 空状态 -->
				<view class="empty-state" v-if="filteredRooms.length === 0 && !waiting">
					<text class="empty-icon">🔍</text>
					<text class="empty-text">暂无房间</text>
					<button class="create-btn" @click="createNewRoom" v-if="activeTab === 'roomList'">创建房间</button>
				</view>
			</view>

			<view class="footer">
				<view class="left">
					<view class="left_item" :class="{ active: activeTab === 'roomList' }"
						@click="switchTab('roomList')">
						<view>房间</view>
						<view>列表</view>
					</view>
					<view class="left_item" :class="{ active: activeTab === 'topTen' }" @click="switchTab('topTen')">
						<view>十佳</view>
						<view>对战</view>
					</view>
					<view class="left_item" :class="{ active: activeTab === 'history' }" @click="switchTab('history')">
						<view>历史</view>
						<view>记录</view>
					</view>
				</view>
				<view class="right">
					<view class="create_btn" @click="createNewRoom">

					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import Nvagatmy from '../../Component/navgatsmy/navgatsmy.vue';
	import {
		getUsetInof,
		getPKarenaList,
		getPKarenaHistory,
		getPKarenaMyHistory
	} from "../../api/outOfTheFree/index.js"
	import {
		playSound
	} from '../../utils/soundSettings';
	import globalWebSocket from '../../utils/globalWebSocket.js';
	export default {
		data() {
			return {
				img: "https://img.jingkakeji.com/img/static/pks.png",
				userInfo: null,
				battleRooms: [],

				priceTabList: [{
					id: 1,
					title: "全部"
				}, {
					id: 2,
					title: "1-300"
				}, {
					id: 3,
					title: "300-500"
				}, {
					id: 4,
					title: "500+"
				}],
				statusTabList: [{
					id: 1,
					title: "等待中"
				}, {
					id: 2,
					title: "对战中"
				}, {
					id: 3,
					title: "我的"
				}],
				priceTabIndex: 0,
				statusTabIndex: 0,

				activeTab: 'roomList',
				waiting: false,

				currentPage: 1,
				totalPages: 1,
				listData: [],
				uid: "tdwnztx",
				lastRequestTime: 0,
				requestDebounceMs: 2000,
				isInitialized: false,
			}
		},
		components: {
			Nvagatmy
		},
		computed: {
			// 复用筛选逻辑，对当前battleRooms进行过滤
			filteredRooms() {
				let result = [...this.battleRooms];
				if (this.activeTab == "history") {
					return result
				}
				// 金额筛选
				if (this.priceTabIndex !== 0) {
					const priceFilter = this.priceTabList[this.priceTabIndex];
					if (priceFilter.title === "1-300") {
						result = result.filter(room => room.total_bean >= 1 && room.total_bean <= 300);
					} else if (priceFilter.title === "300-500") {
						result = result.filter(room => room.total_bean >= 300 && room.total_bean <= 500);
					} else if (priceFilter.title === "500+") {
						result = result.filter(room => room.total_bean >= 500);
					}
				}

				// 状态筛选 - 与status_alias关联
				if (this.statusTabIndex === 0) {
					result = result.filter(room => room.status_alias === '等待中');
				} else if (this.statusTabIndex === 1) {
					result = result.filter(room => room.status_alias === '对战中');
				} else if (this.statusTabIndex === 2 && this.userInfo) {
					// 我的房间筛选：判断房间参与者中是否有当前用户
					result = result.filter(room =>
						room.game_arena_player.some(player => player.user.id === this.userInfo.id)
					);
				}
				return result;
			},

			// 排序后的房间列表
			sortedRooms() {
				const filtered = this.filteredRooms;
				// 历史记录显示正序，其他显示倒序
				if (this.activeTab === 'history') {
					return filtered; // 正序
				} else {
					return filtered.slice().reverse(); // 倒序
				}
			}
		},
		watch: {
			priceTabIndex(newVal, oldVal) {
				if (oldVal !== undefined && newVal !== oldVal) {
					this.resetPageAndLoadData();
				}
			},
			statusTabIndex(newVal, oldVal) {
				if (oldVal !== undefined && newVal !== oldVal) {
					this.resetPageAndLoadData();
				}
			}
		},
		onShow() {
			this.getusers();
			if (!this.isInitialized) {
				this.isInitialized = true;
				this.switchTab(this.activeTab);
			}
			this.initGlobalWebSocket();
		},
		onHide() {
			this.removeWebSocketListeners();
		},
		destroyed() {
			this.removeWebSocketListeners();
		},
		methods: {
			resetPageAndLoadData() {
				this.currentPage = 1;
				this.loadCurrentTabData();
			},

			async switchTab(tab) {
				playSound("https://img.jingkakeji.com/img/static/music/click.mp3")
				this.activeTab = tab;
				this.currentPage = 1;
				await this.loadCurrentTabData();
			},
			async loadCurrentTabData() {
				this.waiting = true;
				try {
					let res;
					switch (this.activeTab) {
						case 'roomList':
							res = await getPKarenaList(this.currentPage);
							break;
						case 'topTen':
							res = await getPKarenaMyHistory(this.currentPage);
							console.log('ten');
							break;
						case 'history':
							res = await getPKarenaHistory(this.currentPage);
							console.log('his');
							break;
					}
					this.battleRooms = res?.data?.data || [];
					this.listData = this.battleRooms;
					this.totalPages = res?.data?.last_page || 1;
				} catch (err) {
					console.error('数据获取失败:', err);
					this.battleRooms = [];
					this.listData = [];
					this.totalPages = 1;
				} finally {
					this.waiting = false;
				}
			},

			handleRoomClick(room) {
				playSound("https://img.jingkakeji.com/img/static/music/click.mp3")
				if (this.activeTab === 'roomList') {
					this.joinRoom(room.id);
				} else {
					uni.navigateTo({
						url: `/pages/pks/overRoom/overRoom?roomId=${room.id}`
					})
				}
			},

			joinRoom(roomId) {
				const room = this.battleRooms.find(r => r.id === roomId);
				if (!room) return;

				const url = room.status === 'waiting' ?
					`/pages/pks/pk/pk` :
					`/pages/pks/pk/pk?roomId=${roomId}`;
				console.log(url);
				uni.navigateTo({
					url
				});
			},
			async loadMore() {
				if (this.currentPage >= this.totalPages) {
					return;
				}

				this.currentPage++;
				this.waiting = true;

				try {
					let res;
					switch (this.activeTab) {
						case 'roomList':
							res = await getPKarenaList(this.currentPage);
							break;
						case 'topTen':
							res = await getPKarenaMyHistory(this.currentPage);
							break;
						case 'history':
							res = await getPKarenaHistory(this.currentPage);
							break;
					}

					const newData = res?.data?.data || [];

					if (newData.length > 0) {
						this.battleRooms = [...this.battleRooms, ...newData];
						this.listData = this.battleRooms;
					}

					this.totalPages = res?.data?.last_page || 1;

				} catch (err) {
					console.error('加载更多失败:', err);
					this.currentPage--;
				} finally {
					this.waiting = false;
				}
			},
			createNewRoom() {
				playSound("https://img.jingkakeji.com/img/static/music/click.mp3")
				uni.navigateTo({
					url: "/pages/pks/chuangpk/chuangpk"
				});
			},

			async getusers() {
				try {
					const res = await getUsetInof();
					this.userInfo = res.data;
				} catch (err) {
					console.error('获取用户信息失败:', err);
				}
			},

			priceTabClick(index) {
				this.priceTabIndex = index;
			},
			statusTabClick(index) {
				this.statusTabIndex = index;
			},
			async getData() {
				const now = Date.now();
				if (now - this.lastRequestTime < this.requestDebounceMs) {
					return;
				}
				this.lastRequestTime = now;
				await this.loadCurrentTabData();
			},

			initGlobalWebSocket() {
				// 初始化全局WebSocket连接
				globalWebSocket.init();

				// 添加消息监听器
				globalWebSocket.on('message', this.handleWebSocketMessage);
			},

			removeWebSocketListeners() {
				// 移除消息监听器
				globalWebSocket.off('message', this.handleWebSocketMessage);
			},

			handleWebSocketMessage(e) {
				// 处理WebSocket消息
				if (this.activeTab === 'roomList' && this.isInitialized) {
					console.log('收到WebSocket消息，刷新数据');
					this.getData();
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.pks_page {
		width: 100vw;
		height: 100vh;
		overflow: hidden;
		background-image: url("https://img.jingkakeji.com/img/static/new_pk/bg.png");
		background-size: cover;
		background-position: center;
		background-repeat: no-repeat;

		.main {
			width: 100%;
			height: calc(100% - 250rpx);
			margin-top: 20rpx;
			display: flex;
			flex-direction: column;
			align-items: center;

			.price_tab {
				width: 95%;
				height: 66rpx;
				border-radius: 75rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				background-image: linear-gradient(to top, #A29DDD, #D5D6F1);

				.price_tab_item {
					width: 160rpx;
					height: 75rpx;
					background-size: contain;
					background-position: center;
					background-repeat: no-repeat;
					text-align: center;
					line-height: 75rpx;
					font-size: 28rpx;
					color: white;
				}

				.active {
					background-image: url("https://img.jingkakeji.com/img/static/new_pk/price_tab_item.png");
				}
			}

			.list_box {
				width: 95%;
				height: 1240rpx;
				background-image: url("https://img.jingkakeji.com/img/static/new_pk/list_bg.png");
				background-size: contain;
				background-position: center;
				background-repeat: no-repeat;
				position: relative;
				display: flex;
				align-items: center;
				justify-content: center;
				margin-top: 60rpx;

				.status_box {
					width: 540rpx;
					height: 66rpx;
					position: absolute;
					top: -60rpx;
					left: calc(50% - 270rpx);
					display: flex;
					justify-content: space-between;

					.status_item {
						width: 170rpx;
						height: 75rpx;
						background-size: contain;
						background-position: center;
						background-repeat: no-repeat;
						background-image: url("https://img.jingkakeji.com/img/static/new_pk/two_tab.png");
						text-align: center;
						line-height: 75rpx;
						font-size: 28rpx;
						color: white;
					}

					.active {
						background-image: url("https://img.jingkakeji.com/img/static/new_pk/two_tab_active.png");
					}
				}

				.lists_box {
					width: 90%;
					height: 1090rpx;
					overflow-y: scroll;
					margin-bottom: 70rpx;

					.scroll_list {
						width: 100%;
						display: flex;
						flex-wrap: wrap;
						justify-content: space-between;

						.list_item {
							width: 310rpx;
							margin-bottom: 16rpx;
							border-radius: 0 0 20rpx 20rpx;
							overflow: hidden;

							.top {
								width: 100%;
								height: 280rpx;
								background-image: url("https://img.jingkakeji.com/img/static/new_pk/list_top.png");
								background-size: cover;
								background-repeat: no-repeat;
								display: flex;
								flex-direction: column;
								align-items: center;

								.header {
									width: 240rpx;
									height: 50rpx;
									background-image: url("https://img.jingkakeji.com/img/static/new_pk/header.png");
									background-size: contain;
									background-position: center;
									background-repeat: no-repeat;
									color: white;
									text-align: center;
									font-size: 26rpx;
									line-height: 46rpx;
								}

								.user_box {
									width: 230rpx;
									height: 60rpx;
									margin-top: 15rpx;
									display: flex;
									align-items: center;
									justify-content: space-evenly;

									.user_item {
										width: 60rpx;
										height: 60rpx;
										background-color: #151229;
										background-size: contain;
										color: white;
										text-align: center;
										line-height: 60rpx;
										font-size: 40rpx;
										font-weight: bold;
										margin: 0 10rpx;
									}
								}

								.tool_list {
									width: 290rpx;
									height: 100rpx;
									margin-top: 44rpx;
									align-self: flex-end;
									overflow: auto;
									display: flex;

									.scroll_tool_list {
										height: 100%;
										display: flex;

										.tool_item {
											width: 110rpx;
											height: 100rpx;
											margin-right: 20rpx;
											display: flex;
											flex-direction: column;

											.img {
												width: 100%;
												height: 60rpx;
												background-size: cover;
												background-position: center;
												background-repeat: no-repeat;
											}

											.price {
												width: 100%;
												height: 40rpx;
												display: flex;
												align-items: center;
												justify-content: space-evenly;
												background: rgba(0, 0, 0, 0.2);

												.icon {
													width: 25rpx;
													height: 25rpx;
													background-image: url("https://img.jingkakeji.com/img/static/new_pk/money.png");
													background-size: contain;
													background-position: center;
													background-repeat: no-repeat;
												}

												.text {
													font-size: 26rpx;
													color: #FBDC3B;
												}
											}
										}
									}
								}
							}

							.bottom {
								width: 100%;
								height: 90rpx;
								background-image: url("https://img.jingkakeji.com/img/static/new_pk/list_bottom.png");
								background-size: cover;
								display: flex;
								justify-content: center;
								align-items: center;

								.list_btn {
									width: 260rpx;
									height: 60rpx;
									background-image: url("https://img.jingkakeji.com/img/static/new_pk/list_btn.png");
									background-size: contain;
									background-position: center;
									background-repeat: no-repeat;
									display: flex;
									justify-content: center;
									align-items: center;

									.icon {
										width: 35rpx;
										height: 35rpx;
										background-image: url("https://img.jingkakeji.com/img/static/new_pk/money.png");
										background-size: contain;
										background-position: center;
										background-repeat: no-repeat;
									}

									.text {
										font-size: 26rpx;
										font-weight: bold;
										color: white;
										margin-left: 10rpx;
										text-shadow: 2px 2px 2px #ea691e;
									}
								}
							}
						}
					}
				}
			}
		}

		.footer {
			width: 100%;
			height: 190rpx;
			background-image: url("https://img.jingkakeji.com/img/static/new_pk/footer.png");
			background-size: cover;
			background-position: center;
			background-repeat: no-repeat;
			position: fixed;
			bottom: 0;
			left: 0;
			display: flex;

			.left {
				width: 50%;
				height: 110rpx;
				margin-top: 70rpx;
				display: flex;
				justify-content: space-around;
				align-items: center;

				.left_item {
					width: 100rpx;
					height: 100rpx;
					font-size: 24rpx;
					color: #bababa;
					text-align: center;
					background-image: url("https://img.jingkakeji.com/img/static/new_pk/bottom_item.png");
					background-size: contain;
					background-position: center;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					cursor: pointer;
					transition: all 0.2s ease;

					&.active {
						color: white;
					}
				}

			}

			.right {
				width: 50%;
				height: 110rpx;
				margin-top: 70rpx;
				display: flex;
				justify-content: center;
				align-items: center;

				.create_btn {
					width: 350rpx;
					height: 120rpx;
					background-image: url("https://img.jingkakeji.com/img/static/new_pk/create_btn.png");
					background-position: center;
					background-size: cover;
					margin-bottom: 20rpx;
					cursor: pointer;
				}
			}
		}

		/* 分页样式 */
		.pagination {
			position: relative;
			z-index: 2;
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 20rpx 0;
			gap: 20rpx;
		}

		.page-btn {
			background-color: rgba(30, 35, 45, 0.8);
			color: #fff;
			border: 1px solid rgba(255, 255, 255, 0.1);
			border-radius: 8rpx;
			padding: 8rpx 20rpx;
			font-size: 22rpx;
		}

		.page-btn:disabled {
			background-color: #636e72;
			color: #b2bec3;
		}

		.page-info {
			color: #fff;
			font-size: 22rpx;
		}

		/* Loading状态 */
		.loading-state {
			width: 100%;
			position: absolute;
			z-index: 2;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 80rpx 20rpx;
		}

		.loading-spinner {
			width: 60rpx;
			height: 60rpx;
			border: 4rpx solid rgba(255, 255, 255, 0.3);
			border-top: 4rpx solid #FBDC3B;
			border-radius: 50%;
			animation: spin 1s linear infinite;
			margin-bottom: 20rpx;
		}

		.loading-text {
			color: #FBDC3B;
			font-size: 28rpx;
			font-weight: 500;
		}

		@keyframes spin {
			0% {
				transform: rotate(0deg);
			}

			100% {
				transform: rotate(360deg);
			}
		}

		/* 空状态 */
		.empty-state {
			width: 100%;
			position: absolute;
			z-index: 2;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 80rpx 20rpx;
		}

		.empty-state .empty-icon {
			font-size: 60rpx;
			color: #636e72;
			margin-bottom: 20rpx;
		}

		.empty-state .empty-text {
			color: #0104bf;
			font-size: 28rpx;
			margin-bottom: 30rpx;
			display: block;
		}

		.create-btn {
			background-color: #2ed573;
			color: white;
			border-radius: 25rpx;
			padding: 12rpx 30rpx;
			font-size: 24rpx;
			border: none;
		}

	}
</style>